import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
import { BASE_URL } from '@/utils/request'

export const fetchPaginatedData = createAsyncThunk('pagination/fetchPaginatedData', async (params, thunkAPI) => {
  const user = JSON.parse(localStorage.getItem('user'))
  const response = await axios.get(`${BASE_URL}/red_growth/keyword`, {
    params,
    headers: {
      'Content-Type': 'application/json',
      token: user.token,
    },
  })
  return response.data.data
})

const keywordSlice = createSlice({
  name: 'keyword',
  initialState: {
    keywords: [],
    paginationConfig: {
      total: 0,
      perPage: 30,
      currentPage: 1,
      lastPage: 0,
    },
    isLoading: true,
    error: null,
  },
  reducers: {
    setKeywords: (state, action) => {
      state.keywords = action.payload
    },
    setPaginationConfig: (state, action) => {
      state.paginationConfig = action.payload
    },
    setIsLoading: (state, action) => {
      state.isLoading = action.payload
    },
  },
  extraReducers: builder => {
    builder
      .addCase(fetchPaginatedData.pending, state => {
        // state.isLoading = true
      })
      .addCase(fetchPaginatedData.fulfilled, (state, action) => {
        state.isLoading = false
        state.keywords = action.payload.data

        state.paginationConfig.total = action.payload.total
        state.paginationConfig.perPage = action.payload.per_page
        state.paginationConfig.currentPage = action.payload.current_page
        state.paginationConfig.lastPage = action.payload.last_page
      })
      .addCase(fetchPaginatedData.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message
      })
  },
})

export const { setKeywords, setPaginationConfig, setIsLoading } = keywordSlice.actions

export const selectKeywords = state => state.keyword.keywords
export const selectIsLoading = state => state.keyword.isLoading
export const selectPaginationConfig = state => state.keyword.paginationConfig

export default keywordSlice.reducer
